package com.mybed.crm.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mybed.crm.common.enums.HttpCodeEnum;
import com.mybed.crm.exception.BaseException;
import com.mybed.crm.mapper.UserMapper;
import com.mybed.crm.mapper.VerificationMapper;
import com.mybed.crm.pojo.dto.LoginDto;
import com.mybed.crm.pojo.pojo.User;
import com.mybed.crm.pojo.pojo.Verification;
import com.mybed.crm.result.LoginResult;
import com.mybed.crm.service.LoginService;
import com.mybed.crm.utils.jwt.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.BackingStoreException;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VerificationMapper verificationMapper;
    @Autowired
    private HttpServletRequest request;

    /**
     * 用户登入验证
     * @param loginDto
     */
    @Override
    public LoginResult login(LoginDto loginDto) {
        Verification verification = verificationMapper.selectOne(Wrappers.<Verification>lambdaQuery().eq(Verification::getUuid, loginDto.getUuid()));
        if(verification==null){
            throw new BaseException("未知错误");
        }
        Long aLong = verification.getTime();
        long l = (System.currentTimeMillis() - aLong)/1000;
        if(l>30L){
             throw new BaseException("验证码超时");
        }
        if(verification.getCode().compareToIgnoreCase(loginDto.getCode())!=0){
            throw new BaseException("验证码错误");
        }
        String clientIp = request.getHeader("X-Real-IP");
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("X-Forwarded-For");
        }
        if (clientIp == null || clientIp.isEmpty() || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        log.info("登入的Ip,{}",clientIp);
        verificationMapper.delete(Wrappers.<Verification>lambdaQuery().eq(Verification::getIpAddr,clientIp));
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<User>();
        wrapper.select(true,User::getPassword,User::getSalt,User::getUserId).eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            throw new BaseException("账户或密码错误");
        }
        String md5 = SecureUtil.md5(password + user.getSalt());
        if(!md5.equals(user.getPassword())){
            throw new BaseException("账户或密码错误");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("userId",user.getUserId().toString());
        String token = JwtUtil.createJWT("43a416fa9c9b453b61175713074324c3", 6000000, map);
        LoginResult result=new LoginResult();
        user.setLoginDate(LocalDateTime.now());
        user.setLoginIp(clientIp);
        userMapper.updateById(user);
        result.setToken(token);
        result.setMsg(HttpCodeEnum.SUCCESS.getErrorMessage());
        result.setCode(HttpCodeEnum.SUCCESS.getCode());
        return result;
    }
}
